/*
 * Copyright (c) HiSilicon (Shanghai) Technologies Co., Ltd. 2023-2023. All rights reserved.
 */

#include "ParamSettingDlg.h"
#include <QLineEdit>
#include <QTableWidgetItem>
#include <QTextCodec>
#include <QFileDialog>
#include <QMessageBox>
#include <QBitArray>
#include <QMessageBox>

namespace BurnDlg {

namespace {
    const int BYTE_SIZE = 8;
    const int INDEX_2 = 2;
    const int SYSTEM_NUMBER_10 = 10;
    const int BINARY_DIGITS_NUMBER_8 = 8;
    const int BINARY_DIGITS_NUMBER_16 = 16;
    const int BINARY_DIGITS_NUMBER_24 = 24;
}

ParamSettingDlg::ParamSettingDlg(QWidget *parent)
    : QMainWindow(parent),
      ui(new Ui::ParamSettingDlg()),
      chipIniRead(nullptr),
      transmissionMode(""),
      chipMode(0),
      parameterStartAddress(0),
      lockStartAddress(0),
      eraseBaseNum(1),
      currentPath(""),
      currentInfo(""),
      isConnect(false)
{
    if (ui == nullptr) {
        return;
    }
    ui->setupUi(this);
    InitUi();
}

ParamSettingDlg::~ParamSettingDlg()
{
}

void ParamSettingDlg::InitUi()
{
    ui->parameterTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->parameterTable->setMouseTracking(true);
    ui->parameterTable->verticalHeader()->setVisible(false);
    ui->parameterTable->horizontalHeader()->setVisible(false); /* Hide List Header */
    ui->parameterTable->setRowCount(0);
    ui->parameterTable->setColumnCount(3);      /* Set 3 List Grid */
    ui->parameterTable->horizontalHeader()->setStretchLastSection(true);
    ui->parameterTable->resizeRowsToContents(); /* Adjust the row height based on the content. */
    ui->parameterTable->resizeColumnsToContents(); /* Cell is not blocked */
    ui->parameterTable->show();
    connect(ui->pbRead, SIGNAL(clicked()), this, SLOT(SlotGetParameterInfoClicked()));
    connect(ui->pbWrite, SIGNAL(clicked()), this, SLOT(SlotSetParameterInfoClicked()));
    connect(ui->parameterSave, SIGNAL(clicked()), this, SLOT(SlotParameterSave()));
    connect(ui->parameterSavePathBut, SIGNAL(clicked()), this, SLOT(SlotParameterSavePathButClicked()));
    connect(ui->parameterSavePath, SIGNAL(textEdited(const QString &)),
            this, SLOT(SlotParameterSavePathTextChange(const QString &)));
    connect(ui->infoArea, SIGNAL(currentIndexChanged(QString)), this, SLOT(SlotSetInfoAreaValue(QString)));
    codec = QTextCodec::codecForName("UTF-8");
}

void ParamSettingDlg::ShowTable(QString group)
{
    if (chipIniRead == nullptr || ui->parameterTable == nullptr) {
        return;
    }
    group = ui->infoArea->currentText() + group;
    ui->parameterTable->clear();
    ui->parameterTable->setRowCount(0);
    totalDigits = 0;
    chipIniRead->beginGroup(group);
    QStringList keys = chipIniRead->childKeys();
    chipIniRead->endGroup();
    parameterInfoList.clear();
    FormUiParameterTableItems(group, keys);

    ui->parameterTable->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    ui->parameterTable->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    ui->parameterSavePath->setText(chipIniRead->value("config/parameterSavePath").toString());
}

void ParamSettingDlg::FormUiParameterTableItems(const QString &group, QStringList &keys)
{
    for (QStringList::iterator item = keys.begin(); item != keys.end(); ++item) {
        ParameterInfo parameter;
        QString key = *item;
        QString value = chipIniRead->value("/" + group + "/" + key, "").toString();
        if (key.contains("-", Qt::CaseSensitive)) {
            key = key.split("-")[1];
            if (key.contains(":", Qt::CaseSensitive)) {
                QStringList keysList = key.split(":");
                key = keysList[0];
                parameter.name = key;
                parameter.digitsNum = keysList[1].toInt();
                parameter.newValue = keysList[2].toInt(Q_NULLPTR, 0x10); /* 2: default value of the parameter */
                totalDigits += parameter.digitsNum;
                parameterInfoList.append(parameter);
            }
        }
        if (value.contains("hide-")) {
            continue;
        }
        int rowCount = ui->parameterTable->rowCount(); /* Gets the number of rows in a form */
        ui->parameterTable->insertRow(rowCount); /* Insert a new row */
        QTableWidgetItem *newQTableWidgetItem = new (std::nothrow)QTableWidgetItem(codec->toUnicode(key.toLatin1()
                                                                                   .replace('*', "\n")));
        if (newQTableWidgetItem == nullptr) {
            return;
        }
        ui->parameterTable->setItem(rowCount, 0, newQTableWidgetItem);
        QStringList vals = value.split("-");
        for (int i = 0; i < vals.size(); i++) {
            if (vals.at(i).contains("lineEdit16")) {
                SetTableWidgetValue(parameter, rowCount, i);
            } else {
                SetTableWidgetItemValue(vals, i, rowCount);
            }
        }
    }
}

void ParamSettingDlg::SetIniSettings(QSettings *fd)
{
    chipIniRead = fd;
}


void ParamSettingDlg::SetTableWidgetValue(ParameterInfo &parameter, int rowCount, int index) const
{
    QLineEdit *qEdit = new (std::nothrow)QLineEdit();
    if (qEdit == nullptr) {
        return;
    }
    qEdit->setStyleSheet("border-width: 0; border-style: outset");
    qEdit->setText(QString::number(parameter.newValue, 0x10));
    ui->parameterTable->setCellWidget(rowCount, index + 1, qEdit);
}

void ParamSettingDlg::SetTableWidgetItemValue(QStringList &vals, int index, int rowCount) const
{
    QTableWidgetItem *newQTableWidgetItem = new (std::nothrow)QTableWidgetItem(codec->toUnicode(vals.at(index)
        .toLatin1().replace('*', "\n")));
    if (newQTableWidgetItem == nullptr) {
        return;
    }
    ui->parameterTable->setItem(rowCount, index + 1, newQTableWidgetItem);
}

void ParamSettingDlg::SlotParameterSavePathButClicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("bin file"),
                                                    ui->parameterSavePath->text(), tr("bin File(*.bin)"));
    if (fileName.isEmpty()) {
        return;
    }

    ui->parameterSavePath->setText(fileName);
    SlotParameterSavePathTextChange(fileName);
}

void ParamSettingDlg::SlotParameterSavePathTextChange(const QString &str)
{
    currentPath = str;
}

void ParamSettingDlg::SetCurrentPath()
{
    if (currentPath.isEmpty()) {
        QString partitionFile = Global::GetAppConfigPath();
        QDir dir(partitionFile);
        QString str = dir.absoluteFilePath("config_mcu/temp/uploadFileTemp.bin");
        ui->parameterSavePath->setText(str);
        SlotParameterSavePathTextChange(str);
    } else {
        ui->parameterSavePath->setText(currentPath);
    }
}

void ParamSettingDlg::SetIsConnect(bool connect)
{
    isConnect = connect;
}

void ParamSettingDlg::ShowInfoAreaUI(bool isEnable) const
{
    ui->infoAreaLabel->setVisible(isEnable);
    ui->infoArea->setVisible(isEnable);
    burnCtrl->SetIsInfoPart(isEnable);
    if (isEnable) {
        ui->infoAreaLayout->insertItem(INDEX_2, ui->infoAreaSpacer);
        ShowQComboBox(chipIniRead, "infoPart", ui->infoArea, SYSTEM_NUMBER_10);
    } else {
        ui->infoAreaLayout->removeItem(ui->infoAreaSpacer);
    }
}

void ParamSettingDlg::SlotGetParameterInfoClicked()
{
    burnCtrl->SetTotalDigits(totalDigits);
    burnCtrl->SetParamStartAddress(parameterStartAddress);
    emit SignalGetParameter();
}

void ParamSettingDlg::SetBurnCtrl(BurnCtrl *burnCtrlNeedSet)
{
    this->burnCtrl = burnCtrlNeedSet;
}

void ParamSettingDlg::SlotSetParameterInfoList(QByteArray byte)
{
    int offset = 0;
    int index = 0;
    const int registerBytes = 4;
    const int registerBits = 32;

    for (int i = 0; i < (byte.size() / registerBytes); i++) {
        uint temp = 0;
        int byteIndex = 0;
        temp |= static_cast<unsigned int>(byte[registerBytes * i]) & 0xff;
        temp |= (static_cast<unsigned int>(byte[registerBytes * i + (++byteIndex)]) & 0xff << BINARY_DIGITS_NUMBER_8);
        temp |= (static_cast<unsigned int>(byte[registerBytes * i + (++byteIndex)]) & 0xff << BINARY_DIGITS_NUMBER_16);
        temp |= (static_cast<unsigned int>(byte[registerBytes * i + (++byteIndex)]) & 0xff << BINARY_DIGITS_NUMBER_24);
        while (registerBits * (i + 1) - offset > 0) {
            int offsetBit = offset % registerBits;
            parameterInfoList[index].newValue = (temp >> offsetBit) &
                    ((0x1 << parameterInfoList[index].digitsNum) - 1);
            if (isInitParameter) {
                parameterInfoList[index].oldValue = parameterInfoList[index].newValue;
            }
            SetProtectionPara(index);
            offset += parameterInfoList[index].digitsNum;
            index++;
        }
    }
    isInitParameter = false;
    UpdatesParameterTable();
}

void ParamSettingDlg::UpdatesParameterTable()
{
    int row = 1;
    int valCol = 1;
    int rowCount = ui->parameterTable->model()->rowCount();
    for (int i = 0; i < parameterInfoList.size(); ++i) {
        ParameterInfo parameterInfo = parameterInfoList.at(i);
        if (row >= rowCount) {
            break;
        }
        QString name = ui->parameterTable->model()->index(row, 0).data().toString();
        if (name == parameterInfo.name) {
            QWidget *widget = ui->parameterTable->cellWidget(row, valCol);
            if (widget == nullptr) {
                emit SignalSetLog(QString(tr("widget is null row: %1 valCol: %2.\n")).arg(row).arg(valCol),
                                  false,
                                  Qt::red);
                return;
            }
            QLineEdit *qline = qobject_cast<QLineEdit *>(widget);
            qline->setText(QString::number(parameterInfo.newValue, 0x10));
            row++;
        }
    }
    emit SignalSetLog(QString(tr("Get parameter successfully.\n")), false, Qt::green);
}

void ParamSettingDlg::SetProtectionPara(int index)
{
    if (protectionPara.name == parameterInfoList[index].name) {
        protectionPara.newValue = parameterInfoList[index].oldValue;
        if (isInitParameter) {
            protectionPara.oldValue = parameterInfoList[index].newValue;
        }
    }
}

bool ParamSettingDlg::GetinfoUnlockData(const QSettings *fd)
{
    Q_UNUSED(fd)
    if (chipIniRead == nullptr) {
        return false;
    }
    infoUnlockList.clear();
    QString infoAreaValue = ui->infoArea->currentText();
    QStringList keyList = chipIniRead->allKeys();
    for (QString key : keyList) {
        if (key.contains(infoAreaValue + "Unlock")) {
            QString valueStr = chipIniRead->value(key).toString();
            DWORD value = valueStr.toULong(Q_NULLPTR, 0x10);
            if (key.contains("-")) {
                key = key.mid(key.indexOf("-") + 1);
            }

            ParameterInfo infoUnlock;
            if (key.contains(":")) {
                infoUnlock.name = key.mid(0, key.indexOf(":"));
                infoUnlock.digitsNum = key.mid(key.indexOf(":") + 1).toUInt() * BURN_START_ADDRESS_BASE_BIT;
                infoUnlock.defaultValue = value;
                infoUnlock.oldValue = value;
            }
            infoUnlockList.append(infoUnlock);
        }
    }
    return true;
}

void ParamSettingDlg::SlotSetParameterInfoClicked()
{
    parameterFilePath = ui->parameterSavePath->text();
    if (parameterFilePath.isEmpty()) {
        QMessageBox::warning(nullptr, stringClass.GetInformation(), tr("The save path cannot be empty."));
        return;
    }
    if (parameterFilePath.toLower().lastIndexOf(".bin") == -1) {
        QMessageBox::warning(nullptr, stringClass.GetInformation(), tr("Please select bin file for storage."));
        return;
    }
    GetConfigurationParameterData();
    QString parameterName = "";
    DWORD maxValue = 0;
    if (!InfoSavaParameterRule(parameterName, maxValue)) {
        QMessageBox::warning(nullptr, stringClass.GetInformation(), QString(tr("%1 cannot be greater than 0x%2."))
                             .arg(parameterName).arg(QString::number(maxValue, 0x10)));
        return;
    }

    if (protectionPara.oldValue != protectionPara.defaultValue &&
            protectionPara.newValue != protectionPara.defaultValue) { // The chip is in the protection state.
        QMessageBox::warning(nullptr, stringClass.GetInformation(), tr("The chip is in protection state,"
                                                                    " please configure the deprotection parameters."));
        return;
    }

    if (!IsSetParameter()) {
        return;
    }

    if (chipMode == CHIP_TYPE_MCU5 && !GetUnlockParameter()) {
        return;
    }
    burnCtrl->SetProtectionPara(protectionPara);
    burnCtrl->SetInfoArea(ui->infoArea->currentData().toInt());
    burnCtrl->SetParameterInfoList(parameterInfoList, infoUnlockList, mapBuf);
    burnCtrl->SetParameterSaveInfo(parameterFilePath, eraseBaseNum);
    burnCtrl->SetIsParameterReset(ui->cbParameterReset->isChecked());
    burnCtrl->SetParamStartAddress(parameterStartAddress);
    emit SignalSetParameter();
}

bool ParamSettingDlg::IsSetParameter()
{
    if (protectionPara.oldValue != protectionPara.defaultValue &&
        protectionPara.newValue == protectionPara.defaultValue) {
        int ret = QMessageBox::question(this, tr("warning"),
                                        tr("Lifting the protection will erase the contents of eflash in sequence."
                                           " Do you confirm to lift the protection?"),
                                        QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Ok);
        if (ret == QMessageBox::Cancel) {
            return false;
        }
    }
    if (IsSetDisableMode()) {
        int ret = QMessageBox::question(this, tr("warning"),
                                        tr("Turn off the read and write permissions of the current connection method."
                                           " You may not be able to access the chip through this connection method."
                                           " Do you want to continue setting up?"),
                                        QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Ok);
        if (ret == QMessageBox::Cancel) {
            return false;
        }
    }
    return true;
}

bool ParamSettingDlg::IsSetDisableMode()
{
    for (int i = 0; i < parameterInfoList.size(); i++) {
        ParameterInfo parameterInfo = parameterInfoList[i];
        if (parameterInfo.name.toLower().contains(transmissionMode)
                && parameterInfo.newValue != parameterInfo.oldValue
                && parameterInfo.newValue != parameterInfo.defaultValue) {
            return true;
        }
    }
    return false;
}

bool ParamSettingDlg::InfoSavaParameterRule(QString &parameterName, DWORD &maxValue)
{
    if (chipIniRead == nullptr) {
        return false;
    }
    QString infoAreaValue = ui->infoArea->currentText();
    QStringList keyList = chipIniRead->allKeys();
    for (QString key : keyList) {
        if (key.contains(infoAreaValue + "RuleMaxValue")) {
            QString valueStr = chipIniRead->value(key).toString();
            DWORD value = valueStr.toULong(Q_NULLPTR, 0x10);
            key = key.mid(key.indexOf("/") + 1);
            if (!IsNOMoreThanMaxValue(key, value, parameterName, maxValue)) {
                return false;
            }
        }
    }
    return true;
}

bool ParamSettingDlg::IsNOMoreThanMaxValue(QString &key, DWORD &value, QString &parameterName, DWORD &maxValue)
{
    foreach(ParameterInfo parameterInfo, parameterInfoList) {
        if (parameterInfo.name == key.trimmed() && parameterInfo.newValue != parameterInfo.defaultValue &&
            parameterInfo.newValue > value) {
            parameterName = parameterInfo.name;
            maxValue = value;
            return false;
        }
    }
    return true;
}

void ParamSettingDlg::GetConfigurationParameterData()
{
    for (int row = 1; row < ui->parameterTable->rowCount(); row++) {
        SetParameterInfoListNewValue(row);
    }

    for (int item = 0; item < infoUnlockList.size(); item++) {
        for (int i = 0; i < parameterInfoList.size(); i++) {
            if (parameterInfoList[i].name == infoUnlockList[item].name) {
                infoUnlockList[item].oldValue = parameterInfoList[i].oldValue;
                infoUnlockList[item].newValue = parameterInfoList[i].newValue;
            }
        }
    }
}

void ParamSettingDlg::SetParameterInfoListNewValue(int row)
{
    for (int item = 0; item < parameterInfoList.size(); item++) {
        if (ui->parameterTable->item(row, 0)->text() == parameterInfoList[item].name) {
            QWidget *widget = ui->parameterTable->cellWidget(row, 1);
            QLineEdit *qline = dynamic_cast<QLineEdit *>(widget);
            parameterInfoList[item].newValue = qline->text().toInt(Q_NULLPTR, 0x10);
            if (protectionPara.name == ui->parameterTable->item(row, 0)->text()) {
                protectionPara.newValue = qline->text().toInt(Q_NULLPTR, 0x10);
            }
            break;
        }
    }
}

void ParamSettingDlg::SetTransmissionMode(QString str)
{
    transmissionMode = str;
}

void ParamSettingDlg::SetChipMode(int chip)
{
    chipMode = chip;
}

bool ParamSettingDlg::GetUnlockParameter()
{
    mapBuf.clear();
    if (infoUnlockList.size() == 0) {
        return false;
    }
    QBitArray bits(infoUnlockList[0].digitsNum);
    int unlockOffset = 0;
    bool isChange = false;
    QStringList lockNames;
    QStringList changeName;

    if (!GetParameterToBuff(lockNames, changeName, bits, unlockOffset, isChange)) {
        return false;
    }

    if (bits.size() > 0) {
        SetMapBuf(bits, unlockOffset, false, isChange);
    }
    if (changeName.size() > 0 && lockNames.size() > 0) {
        int ret = QMessageBox::question(this, tr("warning"),
                                        tr("Modifying the configuration %1 will also lock the corresponding area %2."
                                        "Cannot modify again. Do you want to continue setting?")
                                        .arg(changeName.join(", "))
                                        .arg(lockNames.join(", ")),
                                        QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Ok);
        if (ret == QMessageBox::Cancel) {
            return false;
        }
    }

    return true;
}

bool ParamSettingDlg::GetParameterToBuff(QStringList &lockNames, QStringList &changeName, QBitArray &bits,
                                         int &unlockOffset, bool &isChange)
{
    int offset = 0;
    int index = 0;
    int totalOffset = 0;
    bool isInLockStartAddress = false;
    for (const ParameterInfo info : parameterInfoList) {
        uint newValue = info.newValue;
        bool lock = index < infoUnlockList.size() &&
            infoUnlockList[index].oldValue != infoUnlockList[index].defaultValue;
        if (isInLockStartAddress && lockNames.indexOf(info.name) != -1) {
            newValue = 0;
        }

        if (lock && info.oldValue != newValue) {
            QString lockTips = QString(tr("%1 has been locked, %2 cannot be modified."));
            QMessageBox::warning(nullptr, stringClass.GetInformation(),
                                 lockTips.arg(infoUnlockList[index].name).arg(info.name));
            return false;
        }

        if (info.oldValue != newValue) {
            isChange = true;
            if (!lockNames.contains(infoUnlockList[index].name) && !isInLockStartAddress) {
                lockNames.append(infoUnlockList[index].name);
            }

            if (!changeName.contains(info.name) && !isInLockStartAddress) {
                changeName.append(info.name);
            }
        }
        SetBitValue(info, bits, offset, newValue, totalOffset);
        if (index >= infoUnlockList.size()) {
            continue;
        }

        if (offset >= infoUnlockList[index].digitsNum) {
            SetMapBuf(bits, unlockOffset, lock, isChange);
            isChange = false;
            index++;
            unlockOffset += infoUnlockList[index - 1].digitsNum;
            if (parameterStartAddress + (unlockOffset / BYTE_SIZE) >= lockStartAddress) {
                isInLockStartAddress = true;
            }

            if (index < infoUnlockList.size()) {
                bits.resize(infoUnlockList[index].digitsNum);
            } else {
                bits.resize(abs(totalDigits - totalOffset));
            }
            bits.fill(false);
            offset = 0;
        }
    }

    return true;
}

void ParamSettingDlg::SetBitValue(ParameterInfo info, QBitArray &bits,
    int &offset, const uint &newValue, int &totalOffset) const
{
    for (uint i = 0; i < info.digitsNum; i++) {
        bits.setBit(offset + i, (newValue >> i) & 0x1);
    }

    offset += info.digitsNum;
    totalOffset += info.digitsNum;
}

void ParamSettingDlg::SetMapBuf(QBitArray bits, int unlockOffset, bool lock, bool isChange)
{
    ParameterBuff parameterBuff;
    parameterBuff.buff = DataConvertor::Bits2Bytes(bits);
    parameterBuff.startAddr = parameterStartAddress + (unlockOffset / BYTE_SIZE);
    parameterBuff.lock = lock;
    parameterBuff.isChange = isChange;
    mapBuf.append(parameterBuff);
}

void ParamSettingDlg::GetParameterBaseInfo()
{
    QString infoAreaStr = ui->infoArea->currentText();
    QString startAddressStr = chipIniRead->value(infoAreaStr + "parameterInfo/parameterStartAddress").toString();
    parameterStartAddress = startAddressStr.toULong(Q_NULLPTR, 0x10);
    QString lockStartAddressStr = chipIniRead->value(infoAreaStr + "parameterInfo/lockStartAddress").toString();
    lockStartAddress = lockStartAddressStr.toULong(Q_NULLPTR, 0x10);

    QString eraseBaseNumStr = chipIniRead->value("parameterInfo/eraseBaseNum").toString();
    eraseBaseNum = (eraseBaseNumStr.toULong() != 0) ? eraseBaseNumStr.toULong() : 1;
}

void ParamSettingDlg::GetProtectionPara()
{
    if (chipIniRead == nullptr) {
        return;
    }
    QString flashProtection = chipIniRead->value(ui->infoArea->currentText() + "parameterInfo/flashProtectionName"). \
                              toString();
    if (flashProtection == "") {
        return;
    }
    protectionPara.name = flashProtection.split("-")[0];
    protectionPara.defaultValue = flashProtection.split("-")[1].toInt(Q_NULLPTR, 0x10);
}

void ParamSettingDlg::SlotParameterSave()
{
    parameterFilePath = ui->parameterSavePath->text();
    if (parameterFilePath.isEmpty()) {
        QMessageBox::warning(nullptr, stringClass.GetInformation(), tr("The save path cannot be empty."));
        return;
    }
    GetConfigurationParameterData();
    QString parameterName = "";
    DWORD maxValue = 0;
    if (!InfoSavaParameterRule(parameterName, maxValue)) {
        QMessageBox::warning(nullptr, stringClass.GetInformation(),
                             QString(tr("%1 cannot be greater than 0x%2.")).arg(parameterName). \
                             arg(QString::number(maxValue, 0x10)));
        return;
    }
    /* get parameter bin file */
    if (GetParameterData() != SUCCESS) {
        QMessageBox::information(nullptr, stringClass.GetInformation(),
                                 stringClass.GetNotWriteAgainTips().arg(parameterFilePath));
        return;
    }
    QMessageBox::information(nullptr, stringClass.GetInformation(), tr("Saved successfully."));
}

int ParamSettingDlg::GetParameterData()
{
    QBitArray bits(totalDigits);
    int offset = 0;
    foreach(const ParameterInfo info, parameterInfoList) {
        for (uint i = 0; i < info.digitsNum; i++) {
            bits.setBit(offset + i, (info.newValue >> i) & 0x1);
        }
        offset += info.digitsNum;
    }
    QByteArray a = DataConvertor::Bits2Bytes(bits);
    QFile fileBits(parameterFilePath);
    if (!fileBits.open(QIODevice::WriteOnly)) {
        return FAIL;
    }

    fileBits.write(a.data(), a.size());
    fileBits.close();
    return SUCCESS;
}

void ParamSettingDlg::SetParameterEnableValue(QString group)
{
    group = ui->infoArea->currentText() + group;
    chipIniRead->beginGroup(group);
    QStringList keys = chipIniRead->childKeys();
    chipIniRead->endGroup();
    int index = 0;
    foreach(ParameterInfo parameterInfo, parameterInfoList) {
        if (keys.contains(parameterInfo.name)) {
            QString value = chipIniRead->value("/" + group + "/" + parameterInfo.name, "").toString();
            parameterInfoList[index].defaultValue = value.toInt(Q_NULLPTR, 0x10);
        }
        index++;
    }
}

void ParamSettingDlg::ShowQComboBox(QSettings *fd, QString group, QComboBox *qBox, int baseSystem) const
{
    if (fd == nullptr || qBox == nullptr) {
        return;
    }
    qBox->clear();
    fd->beginGroup(group);
    QStringList keys = fd->childKeys();
    fd->endGroup();
    for (QStringList::iterator item = keys.begin(); item != keys.end(); ++item) {
        QString key = *item;
        QString value = fd->value("/" + group + "/" + key, "").toString();
        if (key.contains("-", Qt::CaseSensitive)) {
            key = key.mid(key.indexOf("-") + 1);
        }
        qBox->addItem(key, value.toInt(Q_NULLPTR, baseSystem));
    }
}

void ParamSettingDlg::SlotSetInfoAreaValue(QString value)
{
    Q_UNUSED(value)
    if (chipIniRead == nullptr) {
        return;
    }
    if (currentInfo == ui->infoArea->currentText()) {
        return;
    }
    parameterInfoList.clear();
    isInitParameter = true;
    GetParameterBaseInfo();
    GetProtectionPara();
    ShowTable("parameter");
    SetParameterEnableValue("parameterEnableValue");
    GetinfoUnlockData(chipIniRead);
    currentInfo = ui->infoArea->currentText();
    SetCurrentPath();
    if (isConnect) {
        SlotGetParameterInfoClicked();
    }
}

}
